/*************************************************************************
  > File Name   : message.hpp
  > Author      : zhongsx
  > Mail        : zhong17hao@gmail.com or  kuai2361425@163.com
  > Created Time: 2016年07月04日 星期一 15时57分23秒
 ************************************************************************/

#ifndef __MESSAGE_HPP__
#define __MESSAGE_HPP__

#include <iostream>
#include <string>
#include <cassert>
#include <cstring>

typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef unsigned char  uint8_t;

class message
{    
public:
    message(int size = 4096 ){
        data_ = NULL;
        wlen = 0;
        mlen = 0;
        //申请内存
        malloc(size);
    }

    ~message(){
        if (data_){
            delete[] data_;
            data_ = NULL;
        }
    }

    uint8_t* get_write_data(){
        
        return data_ + wlen;
    }
    //可写数据大小
    int get_write_size(){
        return mlen - wlen;
    }

    int write(const char* src, int size){
        if (src == NULL || data_ == NULL)
            return -1;
        if (size > mlen)
            malloc(size);
        
        memcpy(data_, src, size);
    
        return size;
    }
    //当message 作为接收数据缓冲时  
    void add_write_size(int size){
        wlen += size;
    }

    uint8_t* get_read_data(){
        return data_;
    }

    int get_read_size(){
        return wlen;
    }

private:
    void malloc(int size){
        if (data_){
            delete[] data_;
            data_ = NULL;
        }

        data_ = new uint8_t[size];
        assert(data_ != NULL);

        memset(data_, 0, size);
        wlen = 0;
        mlen = size;
    }

private:
    uint8_t* data_;
    int     wlen; //已写数据大小
    int     mlen; //当前数据区大小

};

#endif //__MESSAGE_HPP__
